#include "IGameControl.h"
#include "IGrid.h"
#include "IStrategy.h"


void IGameControl::init(IGrid* grid, IStrategy* strategy, IGameConfig config)
{
	assert(m_gameConf.participatorNum >= m_gameConf.playerNum);
	m_grid = grid;
	m_strategy = strategy;
	m_gameConf = config;	
	m_participators.reserve(m_gameConf.participatorNum);
	unsigned int i = 0;
	for (i = 0; i < m_gameConf.playerNum; i++)
	{
		m_participators.push_back(Participator());
		m_participators[i].isAI = false;
	}
	for (; i  < m_gameConf.participatorNum; i++)
	{
		m_participators.push_back(Participator());
		m_participators[i].isAI = true;
	}
}

IGameControl::IGameControl()
	:m_grid(NULL)
	,m_strategy(NULL)
	,m_curParticipatorIndex(0)
	,m_curStep(0)
{
}

IGameControl::~IGameControl(void)
{
}

bool IGameControl::OnSelected(CCPoint p)
{
	if (m_strategy->SelectCell(p, GetCurParticipator()->type))
	{
		m_strategy->ApplyRules();
		if (StepOver())
		{
			NextPlayer();
		}
		if (GetCurParticipator()->isAI)
		{

		}
		return true;
	}
	return false;
	//if (layer->tileAt(p) == NULL)
	//{

	//if (testInt++ % 2 == 0)
	//{
	//	// remove already exist tile
	//	for (int i = 0; i < layer->getLayerSize().width; i++)
	//		for (int j = 0; j < layer->getLayerSize().height; j++)
	//		{
	//			CCPoint point = CCPointMake(i, j);
	//			if (layer->tileGIDAt(point) == 2)
	//				layer->removeTileAt(point);
	//		}
	//	layer->setTileGID(2, p);
	//}
	//else
	//	layer->setTileGID(3, p);
	//}
	return false;
}

void IGameControl::SwitchNextPlayer()
{
	if (m_gameConf.autoSwitchNext)
		return;
	NextPlayer();
	
}


void IGameControl::NextPlayer()
{
	m_curParticipatorIndex++;
	if (m_curParticipatorIndex >= m_participators.size())
		m_curParticipatorIndex = 0;
	this->OnSwitchNextPlayer();
}

Participator* IGameControl::GetCurParticipator()
{
	return &(m_participators[m_curParticipatorIndex]);
}

bool IGameControl::StepOver()
{
	if (++m_curStep >= m_gameConf.stepCount)
	{
		m_curStep = 0;
		return true;
	}
	return false;
}

IGameConfig::IGameConfig()
: stepCount(1),participatorNum(1),
playerNum(1),
autoSwitchNext(true)
{

}
